﻿using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using System;
using System.Configuration;

namespace NCS.IConnect.Cloud.Core
{
    /// <summary>
    /// Provide a CloudStorageAccount resolver to resolve automatically according to the hosting enviroment
    /// </summary>
    public static class CloudStorageAccountResolver
    {
        /// <summary>
        /// Froms the name of the configuration string.
        /// </summary>
        /// <param name="azureConnectionStringName">Name of the azure connection string.</param>
        /// <returns></returns>
        public static CloudStorageAccount FromConfigurationStringName(String azureConnectionStringName)
        {
            CloudStorageAccount cloudStorageAccount = null;

            if (RoleEnvironment.IsAvailable)
            {
                cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting(azureConnectionStringName);
            }
            else
            {
                if (ConfigurationManager.AppSettings[CloudConstants.ConfigurationPropertyNames.CloudStorageName] != null)
                {
                    CloudStorageAccount.TryParse(ConfigurationManager.AppSettings[CloudConstants.ConfigurationPropertyNames.CloudStorageName], out cloudStorageAccount);
                }
                else
                {
                    cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
                }
            }

            return cloudStorageAccount;
        }

        /// <summary>
        /// Sets the configuration setting publisher.
        /// </summary>
        /// <param name="configurationSettingPublisher">The configuration setting publisher.</param>
        public static void SetConfigurationSettingPublisher(Action<string, Func<string, bool>> configurationSettingPublisher)
        {
            CloudStorageAccount.SetConfigurationSettingPublisher(configurationSettingPublisher);
        }
    }
}
